package com.lw.common.license;

import cn.hutool.core.net.NetUtil;
import cn.hutool.system.HostInfo;
import cn.hutool.system.SystemUtil;
import de.schlichtherle.license.*;
import io.micrometer.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.x500.X500Principal;
import java.io.File;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.prefs.Preferences;

public class LicenseVerify {
    private final Logger log = LoggerFactory.getLogger(LicenseVerify.class);
    /**
     *  安装License证书
     *  license.lic:相对路径,绝对路径报错 by lw on 二〇二五年八月三十日 17:21:05
      */
    public synchronized LicenseContent install(LicenseVerifyParam param) {
        LicenseContent result = null;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 1. 安装证书
        try {
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
            licenseManager.uninstall();

            String localMacAddress = NetUtil.getLocalMacAddress();
            if(StringUtils.isEmpty(localMacAddress)) {
                throw new RuntimeException("本地mac地址为空,无法安装license证书");
            }
            result = licenseManager.install(new File("config/license.lic"));
            String info = result.getInfo();
            if (StringUtils.isEmpty(info)) {
                licenseManager.uninstall();
                throw new RuntimeException("抱歉,license描述信息不能为空.");
            }
            if (!info.equalsIgnoreCase(localMacAddress)) {
                licenseManager.uninstall();
                throw new RuntimeException("抱歉,license无法在此mac地址安装.");
            }

            String format1 = MessageFormat.format("证书安装成功，证书有效期：{0} - {1}",
                    format.format(result.getNotBefore()), format.format(result.getNotAfter()));
            System.out.println(format1);
            log.info(format1);
        } catch (Exception e) {
            log.error("证书安装失败: {}", e.getMessage());
        }
        return result;
    }

    // 校验License证书
    public boolean verify() {
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 2. 校验证书
        try {
            LicenseContent licenseContent = licenseManager.verify();
            String format1 = MessageFormat.format("证书校验通过，证书有效期：{0} - {1}",
                    format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter()));
            log.info(format1);
            System.out.println(format1);
            return true;
        } catch (Exception e) {
            log.error("证书校验失败: {}", e.getMessage());
            System.out.println("证书校验失败: " + e.getMessage());
            return false;
        }
    }

    // 初始化证书生成参数 publicCerts.keystore:相对路径,绝对路径报错 by lw on 二〇二五年八月三十日 17:21:05
    private LicenseParam initLicenseParam(LicenseVerifyParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class
                , "config/publicCerts.keystore"
                , param.getPublicAlias()
                , param.getStorePass()
                , null);
        return new DefaultLicenseParam(param.getSubject()
                , preferences
                , publicStoreParam
                , cipherParam);
    }
}
